// 引入axios
import axios from "axios"
// 引入querystring
import qsString from "querystring"
//设置基础地址
let baseUrl = "/api"
// axios请求拦截器
axios.interceptors.request.use(req => {
    if (req.url != "/api/userlogin") {
        // 添加登录token信息
        req.headers.authorization = JSON.parse(sessionStorage.getItem("userInfo")).token || null
    }
    return req
})
// axios响应拦截器
axios.interceptors.response.use(res => {
    // 全局拦截token错误信息
    if (res.data.msg == "请设置请求头,并携带验证字符串" || res.data.msg == "登录已过期或访问权限受限") {
        alert(res.data.msg)
        // 跳转到登录
        window.open("/login")
        return
    }
    return res.data
})

// 封装get方法
export const get = (url, params = {}) => {
    return new Promise((resolve, reject) => {
        axios.get(baseUrl + url, { params })
            .then(res => {
                resolve(res)
            }).catch(err => {
                reject(err)
            })
    })
}

// 封装post方法
export const post = (url, params = {}, isFile = false) => {
    let data = {}
    // 判断是否有文件上传
    if (isFile) {
        data = new FormData()
        for (let i in params) {
            data.append(i, params[i])
        }
    } else {
        data = qsString.stringify(params)
    }
    return new Promise((resolve, reject) => {
        axios.post(baseUrl + url, data)
            .then(res => {
                resolve(res)
            }).catch(err => {
                reject(err)
            })
    })
}

